﻿
using System.Drawing.Printing;
using System.Drawing;
using System.Net.NetworkInformation;
using ZXing;
using System;
using System.Drawing.Imaging;
using System.IO;
using TyMES.Communication;
using System.Threading.Tasks;

namespace TyMES.Services
{
    public class PrintBarcodeService
    {
        private string filePath= "E:\\BarCodeShipment\\barcode.tiff";
        // 默认打印机DPI
        private const int PrinterDpi = 300;

        public async Task GenerateBarcodeForLabel(string barcodeValue, double labelWidthCm, double labelHeightCm)
        {

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            // 假设打印机DPI为300
            int dpi = 300;
            // 将厘米转换为英寸
            double labelWidthInches = labelWidthCm / 6.5;
            double labelHeightInches = labelHeightCm / 6;

            // 计算条码图像的像素尺寸
            int widthInPixels =(int) (labelWidthInches*dpi);
            int heightInPixels = (int)(labelHeightInches*dpi);

            // 创建条码写入器对象
            var writer = new BarcodeWriter
            {
                Format = BarcodeFormat.CODE_128, // 选择条码格式
                Options = new ZXing.Common.EncodingOptions
                {
                    Width = widthInPixels, // 设置条码宽度
                    Height = heightInPixels, // 设置条码高度
                    PureBarcode = true, // 仅生成条码，不包含文本
                    Margin = 10
                }
            };

            // 生成条码图像
            Bitmap barcodeBitmap = writer.Write(barcodeValue);

            // 保存条码图像到文件
            barcodeBitmap.Save(filePath, ImageFormat.Tiff); // 保存为tiff格式
        }

        public async Task<ResponseBase> PrintTiffBarcode(float labelWidthCm, float labelHeightCm,string materialName,string driveType,string shipmentCode)
        {
            try
            {
                // 确保文件存在
                if (!File.Exists(filePath))
                {
                    Console.WriteLine("File does not exist: " + filePath);
                    return new ResponseBase(false, "文件不存在");
                }

                int pixelsWidth = (int)(labelWidthCm * PrinterDpi/6);
                int pixelsHeight = (int)(labelHeightCm * PrinterDpi / 6);

                // 创建Image对象
                Image barcodeImage = Image.FromFile(filePath);

                // 创建打印文档
                using (PrintDocument printDocument = new PrintDocument())
                {
                    //设置默认打印机
                    printDocument.PrinterSettings.PrinterName = "\\\\10.53.27.85\\ZT230"; 
                    // 打印前事件
                    printDocument.BeginPrint += new PrintEventHandler(PrintDocument_BeginPrint);
                    // 打印页面事件
                    printDocument.PrintPage += (sender, e) =>
                    {
                        // 计算图像的缩放比例以适应标签纸尺寸
                        float scaleX = pixelsWidth / (float)barcodeImage.Width;
                        float scaleY = pixelsHeight / (float)barcodeImage.Height;
                        float scale = Math.Min(scaleX, scaleY);

                        // 根据缩放比例调整图像尺寸
                        int width = (int)(barcodeImage.Width * scale);
                        int height = (int)(barcodeImage.Height * scale);

                        string header1 = driveType;
                        string header2 = materialName;
                        string header3 = shipmentCode;

                        Font headerFont1 = new Font("SimHei", 7, FontStyle.Bold); // 可以根据需要修改字体和大小
                        Font headerFont2 = new Font("SimHei", 9, FontStyle.Bold);
                        Font headerFont3 = new Font("SimHei", 9, FontStyle.Bold);
                        // 计算表头文本的尺寸
                        SizeF headerSize1 = e.Graphics.MeasureString(header1, headerFont1);
                        SizeF headerSize2 = e.Graphics.MeasureString(header2, headerFont2);
                        SizeF headerSize3 = e.Graphics.MeasureString(header1, headerFont3);

                        // 绘制第一个表头文本
                        e.Graphics.DrawString(header1, headerFont1, Brushes.Black,
                            new PointF(44, 8));

                        // 绘制第二个表头文本
                        e.Graphics.DrawString(header2, headerFont2, Brushes.Black,
                            new PointF(44, 18));

                        // 绘制缩放后的图像
                        e.Graphics.DrawImage(barcodeImage,
                            new Rectangle(
                                42,
                                33,
                                width,
                                height
                            )
                        );
                        e.Graphics.DrawString(header3, headerFont3, Brushes.Black,
                            new PointF(55, 68));
                    };

                    // 打印文档
                    printDocument.Print();
                    barcodeImage.Dispose();
                    
                }
                return new ResponseBase(true, "");
            }
            catch (Exception ex)
            {
               return new ResponseBase(true, "打印失败"+ex.Message);
            }
        }

        private void PrintDocument_BeginPrint(object sender, PrintEventArgs e)
        {
            // 可以在这里设置打印文档的初始状态
        }

        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            // 从filePath获取Image对象
            Image barcodeImage = Image.FromFile(filePath);

            // 计算图像的缩放比例以适应页面
            float scaleX = (float)e.PageSettings.PrintableArea.Width / barcodeImage.Width;
            float scaleY = (float)e.PageSettings.PrintableArea.Height / barcodeImage.Height;
            float scale = Math.Min(scaleX, scaleY);

            // 计算缩放后的图像尺寸
            int width = (int)(barcodeImage.Width * scale);
            int height = (int)(barcodeImage.Height * scale);

            // 绘制图像
            e.Graphics.DrawImage(barcodeImage,
                                 new Rectangle(0, 0, width, height),
                                 new Rectangle(0, 0, barcodeImage.Width, barcodeImage.Height),
                                 GraphicsUnit.Pixel);

            // 确保释放资源
            barcodeImage.Dispose();
        }
    }
}
